from flask import Blueprint, jsonify, request

from app.cache.iron_redis import IronRedis
from app.controllers.response.response import SuccessResult
from app.exts import ironman_redis
from app.exts import mongo
from app.services.business import gaolu_biz_service, time_service
import datetime
from app.services.business import hanfan_biz_service
from app.services.chart import chart_instance_dict
from app.services.dal import hanfan_dao_service
from app.utils.sys_utils import get_time_round_and_adjust, string_to_bool, string_to_num, GaoLuEncoder
from app.models.po.hanfan.hanfan_predict_po import HanFanPredictPO
from app.utils import string_util
import pandas as pd

bp = Blueprint('indicator_controller', __name__, url_prefix="/api/v1/indicator")
ping_bp = bp

@ping_bp.route("/latest",methods=['get'])
def get_latest_time():
    item_name = request.args.get("itemName")
    start,end,current = time_service.get_latest_time(item_name)
    return SuccessResult(detail={"start":start,"end":end,"current":current}, encoder=GaoLuEncoder)

@ping_bp.route("/chart", methods=['get'])
def chart_display():
    """
    抽象图表展示层,根据名字定位到具体业务
    :return:
    """
    name = request.args.get("name")
    start = request.args.get("start")
    end = request.args.get("end")

    chart_instance = chart_instance_dict[name]
    data = chart_instance.generate(start=start,end=end)

    return SuccessResult(detail=data,encoder=GaoLuEncoder)

@ping_bp.route("/downloadHistory", methods=['get'])
def chart_download():
    """
    抽象图表展示层,根据名字定位到具体业务
    :return:
    """
    name = request.args.get("name")
    start = request.args.get("start")
    end = request.args.get("end")

    chart_instance = chart_instance_dict[name]
    data = chart_instance.download(start=start,end=end)

    import io
    from flask import make_response, send_file

    out = io.BytesIO()
    writer = pd.ExcelWriter(out, engine='xlsxwriter')
    data.to_excel(excel_writer=writer, index=False, sheet_name='示例')
    writer.close()
    # go back to the beginning of the stream
    out.seek(0)
    response = make_response(
        send_file(out, attachment_filename=start + "至" + end + "历史数据.xlsx", as_attachment=True))

    return response

